# -*- coding:utf8 -*-

import time
import json
from flask import Flask,render_template,request,url_for, redirect, jsonify
from api import Token, Server, Platform

app = Flask(__name__)

def auth():
    return Token('admin','aipuip662012','adminTenant')

@app.route('/')
def index():
    return render_template("index.html")

@app.route('/vps/create',methods=['POST'])
def vps_create():
    serverName="S_%s"%int(time.time())
    imageId="1d1c01af-3b14-491e-a1ac-1c5ea017ec11"
    flavorId="2"
    securityGroup="default"
    publicKey="key-admin"
    tokrn=auth()
    serverAcc=Server(tokrn)
    rs=serverAcc.create(serverName, imageId, flavorId, securityGroup, publicKey)
    if rs:
        serverId=rs['server']['id']
        return redirect(url_for('server_page',server_id=serverId))
    return "access error"


def get_server_info(server_id):
    token=auth()
    serverAcc=Server(token,server_id=server_id)
    info=serverAcc.detail()
    return info

def format_server(server):
    server_properties=[]
    server_properties.append(dict(key=u'编号',value=server["id"]))
    server_properties.append(dict(key=u"服务器名",value=server["name"]))
    server_properties.append(dict(key=u"IP地址",value=server["addresses"]["admin"][0]["addr"]))
    server_properties.append(dict(key=u"状态",value=u"激活"))
    return server_properties


@app.route('/vps/server/<server_id>')
def server_page(server_id):
    server=get_server_info(server_id)
    if server["server"]["status"] not in ["ACTIVE",]:
        need_check=True
    else:
        ppts=format_server(server["server"])
    return render_template("server.html",**locals())


@app.route('/server/<server_id>')
def server_info(server_id):
    server=get_server_info(server_id)
    return jsonify(server=server["server"])

@app.route('/vps/list')
def server_list():
    token=auth()
    sacc=Server(token)
    serversResults=sacc.list()
    servers=serversResults["servers"]
    return render_template("all_server.html",**locals())

@app.route("/vps/delete/<server_id>")
def server_delete(server_id):
    token=auth()
    serverAcc=Server(token,server_id=server_id)
    serverAcc.delete()
    return jsonify(r=True)

@app.route("/vps/all")
def vps_all():
    token=auth()
    pacc=Platform(token)
    imgResults=pacc.image_list()
    imgs=imgResults["images"]
    flavorResults=pacc.flaver_list()
    flavors=flavorResults["flavors"]
    return render_template("flavor.html",**locals())

if __name__ == '__main__':
    app.run(host="0.0.0.0",debug=True)
